package com.itheima.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CommentMapper;
import com.itheima.entity.Result;
import com.itheima.pojo.Comment;
import com.itheima.pojo.User;
import com.itheima.service.CommentService;
import com.itheima.service.UserService;
import com.itheima.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author hrz
 * @version 1.0
 * @date 2020-08-07 9:11
 */
@RestController
@RequestMapping("/web/comment")
@CrossOrigin(allowCredentials="true", allowedHeaders="*", methods={RequestMethod.GET,RequestMethod.POST}, origins="*")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    @Resource
    private CommentMapper commentMapper;

    // 增加评论
    /*
    eg:
    Request Payload:
    {
        "userUid": "137ea1156c6cc48168a1c6b45f9e2d5c",
        "content": "reply test",
        "blogUid": "495a4f850dd47a33f2846643b7fdb481",
        "toUid": "600a2d705df5945cdd788a7d1b7bffa3",
        "toUserUid": "137ea1156c6cc48168a1c6b45f9e2d5c",
        "source": "BLOG_INFO"
    }
    */
    /*
    response:
    {
        "code": "success",
        "data": {
            "userUid": "137ea1156c6cc48168a1c6b45f9e2d5c",
            "toUid": "600a2d705df5945cdd788a7d1b7bffa3",
            "firstCommentUid": "600a2d705df5945cdd788a7d1b7bffa3",
            "toUserUid": "137ea1156c6cc48168a1c6b45f9e2d5c",
            "content": "reply test",
            "blogUid": "495a4f850dd47a33f2846643b7fdb481",
            "source": "BLOG_INFO",
            "user": {
                "userName": "moguBlog_GITEE_7527437",
                "passWord": "972d768bb099b1de8fd2362275256fac",
                "nickName": "黄润梓",
                "gender": "0",
                "avatar": "62e4b99c03fde95cc5ea21262ee05ba6",
                "loginCount": 0,
                "validCode": "0368ccb04979449d9caa175448ca8e74",
                "source": "GITEE",
                "uuid": "7527437",
                "lastLoginTime": "2020-08-14 11:04:42",
                "lastLoginIp": "119.79.228.192",
                "commentStatus": 1,
                "startEmailNotification": 0,
                "os": "Windows",
                "browser": "Chrome-84.0.4147.105",
                "ipSource": "中国|湖北省|武汉市|鹏博士",
                "userTag": 0,
                "photoUrl": "http://demopicture.moguit.cn//blog/admin/jpg/2020/8/14/1597374282295.jpg",
                "uid": "137ea1156c6cc48168a1c6b45f9e2d5c",
                "status": 1,
                "createTime": "2020-08-14 11:04:42",
                "updateTime": "2020-08-14 11:04:42"
            },
            "uid": "20ef11449ab5e3b878539aed56f31931",
            "status": 1,
            "createTime": "2020-08-14 11:30:46",
            "updateTime": "2020-08-14 11:30:46"
        }
     }
     */
    //@RequestMapping("/add")
    //public Result add(@RequestBody Comment comment) {
    //    Comment add = null;
    //    try {
    //        add = commentService.add(comment);
    //    } catch (Exception e) {
    //        e.printStackTrace();
    //        return new Result("error", "新增评论失败");
    //    }
    //    return new Result("success", comment);
    //}
    //原版
    @RequestMapping("/add")
    public Result add(@RequestBody Comment comment) {
        String add = commentService.add(comment);
        if ("failed".equals(add)) {
            return new Result("error", "新增评论失败");
        }
        return new Result("success", "新增评论成功");
    }
    
    // 关闭邮件通知
    // 在用户表中
    @RequestMapping("/closeEmailNotification/{userUid")
    public Result close(@PathVariable(value = "userUid")String userUid) {
        User user = new User();
        String s = userService.closeEmailNotification(user);
        if ("failed".equals(s)) {
            return new Result("error", "关闭右键提醒失败");
        }
        return new Result("success", "关闭邮件提醒成功");
    }

    // 删除评论
    @RequestMapping("/delete")
    public Result delete(@RequestBody Comment comment) {
        String deleteResult = commentService.delete(comment);
        if ("failed".equals(deleteResult)) {
            return new Result("error", "删除评论失败");
        }
        return new Result("success","删除评论成功");
    }

    // 获取评论列表
    /*
    Request Payload:
    {
        "source": "BLOG_INFO",
        "blogUid": "495a4f850dd47a33f2846643b7fdb481",
        "currentPage": 1,
        "pageSize": 10
    }
     */
    /*
    
     */
    // 含回复(回复也是评论)
    @PostMapping("/getList")
    public Result getList(@RequestBody Map<String,Object> paramMap) {
        // 查询所有一级评论
        String blogUid = (String) paramMap.get("blogUid");
        String source = (String) paramMap.get("source");
        Example example = new Example(Comment.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(blogUid)) {
            // 条件1:和传入Comment的BlogUid类似
            criteria.andLike("blogUid", "%" + blogUid + "%");
        }
        // 条件2:和传入Comment的source相等
        criteria.andEqualTo("source",source);
        // 查询满足上面两个条件的List<Comment>
        paramMap.putIfAbsent("currentPage", 1);
        Integer currentPage = (Integer) paramMap.get("currentPage");
        paramMap.putIfAbsent("pageSize", 10);
        Integer pageSize = (Integer) paramMap.get("pageSize");

        PageHelper.startPage(currentPage,pageSize);
        Page<Comment> list = (Page<Comment>) commentMapper.selectByExample(example);
        //List<Comment> list = commentMapper.selectByExample(example);

        
        // 递归查询一级评论下的所有回复,以及所有回复的回复
        Map<String, List<Comment>> toCommentListMap = new HashMap<>();
        for (int a = 0; a < list.size(); a++) {
            List<Comment> tempList = new ArrayList<>();
            for (int b = 0; b < list.size(); b++) {
                if (list.get(a).getUid().equals(list.get(b).getToUid())) {
                    tempList.add(list.get(b));
                }
            }
            toCommentListMap.put(list.get(a).getUid(), tempList);
        }
        List<Comment> firstComment = new ArrayList<>();
        list.forEach(item -> {
            if (StringUtils.isEmpty(item.getToUid())) {
                firstComment.add(item);
            }
        });
        
        List<Comment> commentReplys = selectgetCommentReplys(firstComment, toCommentListMap);
        Page<Comment> commentPage = (Page<Comment>) commentReplys;
        //Page<Comment> commentPage = (Page<Comment>)getCommentReplys(firstComment, toComment ListMap);
        return new Result("success", commentPage);
    }

    // 获取用户的评论列表和回复






    // 获取用户点赞信息

    // 举报评论


    /**
     * 递归获取评论所有回复(以及回复的回复等)
     *
     * @param list 要处理的评论列表对象(不含replyList)
     * @param toCommentListMap 一个map集合,用于存储评论/回复的uid 和 其回复列表的对应关系    Map键为 评论的uid,值为 该评论下的回复列表
     * @return 评论列表对象(内已含replyList)
     */
    private List<Comment> selectgetCommentReplys(List<Comment> list, Map<String, List<Comment>> toCommentListMap) {
        if (list == null || list.size() == 0) {
            return new ArrayList<>();
        } else {
            list.forEach(item -> {
                String commentUid = item.getUid();
                List<Comment> replyCommentList = toCommentListMap.get(commentUid);
                item.setReplyList(selectgetCommentReplys(replyCommentList, toCommentListMap));
            });
            return list;
        }
    }
}

